package com.springinaction.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

@SuppressWarnings("deprecation")
public class CRUDDao implements SpitterDao{
	

	private static final String SQL_INSERT_SPITTER = "insert into spitter (username, password, fullname, email) values (?, ?, ?, ?)";

	private static final String SQL_SELECT_SPITTER = ""
	          + "select id, username, password, fullname from spitter";

	private static final String SQL_SELECT_SPITTER_BY_ID = SQL_SELECT_SPITTER
	          + " where id=?";

	
	private SimpleJdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void save(Spitter spitter) {
		jdbcTemplate.update(SQL_INSERT_SPITTER, spitter.getUsername(),spitter.getPassword(),spitter.getFullname(),spitter.getEmail());
	}

	@Override
	public Spitter getById(long id) {
		
		return jdbcTemplate.queryForObject(SQL_SELECT_SPITTER_BY_ID, 
				new ParameterizedRowMapper<Spitter>() {
					@Override
					public Spitter mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Spitter spitter = new Spitter();
						spitter.setId(rs.getLong(1));
						spitter.setUsername(rs.getString(2));
						spitter.setPassword(rs.getString(3));
						spitter.setFullname(rs.getString(4));
						return spitter;
					}
				}, id);
	}

	
}
